<template>
    <div>
        <Card>
            <Row class="form-row">
                <Form :model="filters" ref="form1" label-position="right" :label-width="90" inline>
                    <FormItem label="物业名称" prop="name">
                        <div class="filters-input">
                            <Input v-model="filters.name" placeholder="物业名称" />
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="ios-search" size="large" @click="handleQuery('form1')">
                            搜索
                        </Button>
                    </FormItem>
                </Form>
            </Row>
            <Row class="form-row">
                <Button type="primary" icon="md-add" size="large" @click="handleAdd()">
                    新增
                </Button>
            </Row>

            <el-table stripe border :loading="tableLoading" :data="tableData" size="large" ref="table"
                      style="width: 100%">
                <template slot="empty">暂无数据</template>
                <el-table-column prop="name" label="物业名称"></el-table-column>
                <el-table-column prop="propertyNo" label="域名地址"></el-table-column>
                <el-table-column prop="address" label="联系地址"></el-table-column>
                <el-table-column prop="smsCount" label="短信数量"></el-table-column>
                <el-table-column prop="smsAutograph" label="短信签名"></el-table-column>
                <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleAdd(scope.row.id)">修改</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </Card>

        <Modal v-model="formVisible" :mask-closable="false" :closable="false" :title="modal && modal.id ? '修改' : '新增'"
               width="900">
            <Form :model="modal" :rules="rule" ref="form2" label-position="right" :label-width="110" class="myOpenFrom">
                <FormItem label="服务商" prop="parentId">
                    <Select v-model="modal.parentId" placeholder="服务商" size="large"
                            :disabled="modal && modal.id ? true : false">
                        <Option v-for="item in modal.deptList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="物业名称" prop="name">
                    <Input v-model="modal.name" placeholder="物业名称" size="large"/>
                </FormItem>

                <FormItem label="域名" prop="propertyNo">
                    <Input v-model="modal.propertyNo" placeholder="物业编号" size="large"/>
                </FormItem>
                <FormItem label="短信签名" prop="smsAutograph">
                    <Input v-model="modal.smsAutograph" placeholder="短信签名" size="large"/>
                </FormItem>
                <FormItem label="联系地址" prop="address">
                    <Input v-model="modal.address" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           placeholder="联系地址" size="large"/>
                </FormItem>
                <FormItem label="登录界面背景图片">
                    <el-upload @click.native=loginPicName(modal.name)
                               accept="image/jpeg,image/jpg,image/png"
                               ref="upload"
                               class="avatar-uploader"
                               :headers="{'x-access-token':token}"
                               :action="act"
                               :show-file-list="false"
                               :data="loginPicUrl"
                               :disabled="disabledOne"
                               :on-success="handleAvatarSuccess"
                               :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" v-bind:src="imageUrl" class="avatar-oneImg">
                        <i v-else class="el-icon-plus avatar-uploader-icon-oneImg"></i>
                    </el-upload>
                    <p>建议尺寸为1920 X 1080px,支持jpg,jpeg,png格式</p>
                    <input type="hidden" name="loginPic" v-model="modal.loginPic"/>
                </FormItem>
                <Row>
                    <Col span="13">
                        <FormItem label="logo大图片">
                            <el-upload @click.native=logoPicName(modal.name)
                                       accept="image/jpeg,image/jpg,image/png"
                                       ref="upload"
                                       class="avatar-uploader"
                                       :headers="{'x-access-token':token}"
                                       :action="act"
                                       :show-file-list="false"
                                       :disabled="disabledTwo"
                                       :data="logoPicUrl"
                                       :on-success="handleAvatarSuccess1"
                                       :before-upload="beforeAvatarUpload1">
                                <img v-if="imageUrl1" v-bind:src="imageUrl1" class="avatar-twoImg">
                                <i v-else class="el-icon-plus avatar-uploader-icon-twoImg"></i>
                            </el-upload>
                            <p>建议尺寸为312 X 87px,支持jpg,png,jpeg格式</p>
                            <input type="hidden" name="logoPic" v-model="modal.logoPic"/>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="logo小图片">
                            <el-upload @click.native=logoMinPicName(modal.name)
                                       accept="image/jpeg,image/jpg,image/png"
                                       ref="upload"
                                       class="avatar-uploader"
                                       before-upload="handleImagesUrlBefore"
                                       :headers="{'x-access-token':token}"
                                       :action="act"
                                       :show-file-list="false"
                                       :disabled="disabledThree"
                                       :data="logoMinPicUrl"
                                       :on-success="handleAvatarSuccess2"
                                       :before-upload="beforeAvatarUpload2">
                                <img v-if="imageUrl2" v-bind:src="imageUrl2" class="avatar-threeImg">
                                <i v-else class="el-icon-plus avatar-uploader-icon-threeImg"></i>
                            </el-upload>
                            <p>建议尺寸为91 X 91px,支持jpg,png,jpeg格式</p>
                            <input type="hidden" name="logoMinPic" v-model="modal.logoMinPic"/>
                        </FormItem>

                    </Col>
                </Row>

            </Form>

            <div slot="footer">
                <Button type="text" size="large" @click="onCancel">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit" :loading="formLoading">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import baseURL from '_conf/url'
    import Cookies from 'js-cookie'
    import {TOKEN_KEY} from '@/libs/util'

    const token = Cookies.get(TOKEN_KEY)
    const act = baseURL + "/common/uploadImg"

    //校验规则
    const rules = {
        name: [
            {
                required: true,
                message: "请输入物业名称",
                trigger: "blur"
            }
        ],
        address: [
            {
                required: true,
                message: "请输入地址",
                trigger: "blur"
            }
        ],


        propertyNo: [
            {
                required: true,
                message: "请输入域名",
                trigger: "blur"
            }
        ],

        parentId: [
            {
                required: true,
                message: "请选择服务商",
                type: "number",
                trigger: "blur"
            }
        ]
    };

    //加载数据
    let loadData = function () {
        if (this.tableLoading) return;
        this.tableLoading = true;
        let params = this.filters;
        params.pageNum = this.pageNum;
        params.pageSize = this.pageSize;
        params.typeInt = 2;

        //与后台交换数据
        this.postRequest("/api/dept/loadData", params).then(res => {
            this.tableLoading = false;
            if (res.code == 20000) {
                this.tableData = res.data.list;
                this.pageTotal = res.data.total;
            } else {
                this.tableData = [];
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    //查询
    let handleQuery = function (name) {
        this.filters.pageNum = 1;
        this.$refs[name].validate(valid => {
            if (valid) {
                this.loadData();
            }
        });
    };


    //打开页面
    let handleAdd = function (id) {
        let url = "/api/dept/openModel?typeInt=2";
        if (id) {
            url = "/api/dept/openModel?typeInt=2&id=" + id;
        }
        this.modal = {"typeInt": "2"};
        this.getRequest(url).then(res => {
            console.log(res);
            this.tableLoading = false;
            if (res.code == 20000) {
                if (res.data.list.length == 1) {
                    this.modal.parentId = res.data.list[0].id;
                }

                if (res.data.dept) {
                    this.modal = res.data.dept;
                    res.data.dept.parentId = parseInt(res.data.dept.parentId);
                    res.data.dept.phone = parseInt(res.data.dept.phone);
                    this.imageUrl2 = res.data.dept.logoMinPic;
                    this.imageUrl1 = res.data.dept.logoPic;
                    this.imageUrl = res.data.dept.loginPic;
                }
                this.modal.deptList = res.data.list;
                this.formVisible = true;
            } else {
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    //保存
    let save = function () {
        this.postRequest("/api/dept/saveOrUpdate", this.modal).then(res => {
            this.tableLoading = false;
            if (res.code == 20000) {
                this.$Message.success('操作成功！');
                this.formLoading = false;
                this.formVisible = false;
                // this.$refs["form1"].resetFields();
                this.imageUrl = null;
                this.imageUrl1 = null;
                this.imageUrl2 = null;
                this.$refs.upload.clearFiles();
                this.$refs.upload1.clearFiles();
                this.$refs.upload2.clearFiles();
                this.loadData();
            } else {
                this.formLoading = false;
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    //保存
    let handleSubmit = function () {

        this.$refs["form2"].validate(valid => {
            if (valid) {
                this.formLoading = true;
                this.save();
            }
        });
    };

    let onCancel = function () {

        this.$refs["form2"].resetFields();
        this.formLoading = false;
        this.formVisible = false;
        this.imageUrl = null;
        this.imageUrl1 = null;
        this.imageUrl2 = null;
    };

    export default {
        data() {
            return {
                token:token,
                loginPicUrl: {},
                logoPicUrl: {},
                logoMinPicUrl: {},
                disabledOne: true,
                disabledTwo: true,
                disabledThree: true,
                act: act,
                imageUrl: '',
                imageUrl1: '',
                imageUrl2: '',

                //查询条件
                filters: {},
                //页码
                pageNum: 1,

                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,

                //验证规则
                rule: rules,

                //表格数据
                tableData: [],
                //数据表格隐藏那个状态
                tableLoading: false,
                //对话框隐藏状态
                formVisible: false,
                //表单提交状态
                formLoading: false,
                modal: {}
            };
        },
        created: function () {
            if (this.tableLoading) return;
            this.tableLoading = true;
            let params = this.filters;
            params.pageNum = this.pageNum;
            params.pageSize = this.pageSize;
            params.typeInt = 2;
            //与后台交换数据
            this.postRequest("/api/dept/loadData", params).then(res => {
                this.tableLoading = false;
                if (res.code == 20000) {
                    this.tableData = res.data.list;
                    this.pageTotal = res.data.total;
                } else {
                    this.tableData = [];
                    this.$Message.error({
                        content: res.message,
                        duration: 5
                    });
                }
            });
        },
        methods: {


            handleAvatarSuccess(res, file) {
                this.modal.loginPic = res;
                this.imageUrl = URL.createObjectURL(file.raw);
            },


            beforeAvatarUpload(file) {

                const isSize = new Promise(function (resolve, reject) {

                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();

                    img.onload = function () {
                        let valid = img.width <= 1920 && img.height <= 1080;
                        valid ? resolve() : reject();
                    }
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$Message.info({
                        content: '图片长宽不能大于1920X1080',
                        duration: 5,
                        closable: true
                    });
                    return Promise.reject();
                });

                return isSize;


            },

            handleAvatarSuccess1(res, file) {
                this.modal.logoPic = res;
                this.imageUrl1 = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload1(file) {


                const isSize = new Promise(function (resolve, reject) {

                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width <= 312 && img.height <= 87;
                        valid ? resolve() : reject();
                    }
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$Message.info({
                        content: '图片长宽不能大于312X87',
                        duration: 5,
                        closable: true
                    });
                    return Promise.reject();
                });
                return isSize
            },
            handleAvatarSuccess2(res, file) {
                this.modal.logoMinPic = res;
                this.imageUrl2 = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload2(file) {
                const isSize = new Promise(function (resolve, reject) {

                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width <= 91 && img.height <= 91;
                        valid ? resolve() : reject();
                    }
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$Message.info({
                        content: '图片长宽不能大于91X91',
                        duration: 5,
                        closable: true
                    });
                    return Promise.reject();
                });
                return isSize

            },


            loadData,
            save,
            handleQuery,
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
            //删除按钮
            handleDelete: function (id) {
                this.$Modal.confirm({
                    title: "提示",
                    content: "确定删除该条记录？",
                    onOk: () => {
                        this.getRequest("/api/dept/delete/?id=" + id).then(res => {
                            this.tableLoading = false;
                            if (res.code == 20000) {
                                this.$Message.success("删除成功!");
                                this.pageNum = 1;
                                this.loadData();
                            } else {
                                this.$Message.error({
                                    content: res.message,
                                    duration: 5
                                });
                            }
                        });
                    },
                    onCancel: () => {
                        // this.$Message.info('Clicked cancel');
                    }
                });

            },
            //    返回图片一 name
            loginPicName: function (name) {
                console.log(name)
                if (!name) {
                    this.disabledOne = true;
                    this.$Message.warning('请输入物业名！');
                    return
                } else {
                    this.loginPicUrl = {
                        fileName: "deptImage/"+name+"loginPic"
                    }
                    this.disabledOne = false;
                    console.log(this.loginPicUrl);
                }
            },
            //    返回图片二 name
            logoPicName: function (name) {
                if (!name) {
                    this.disabledTwo = true;
                    this.$Message.warning('请输入物业名！');
                    return
                } else {
                    this.logoPicUrl = {
                        fileName: "deptImage/"+name+"logoPic"
                    }
                    this.disabledTwo = false;
                    console.log(this.logoPicUrl);
                }
            },
            //    返回图片三 name
            logoMinPicName: function (name) {
                if (!name) {
                    this.disabledThree = true;
                    this.$Message.warning('请输入物业名！');
                    return
                } else {
                    this.logoMinPicUrl = {
                        fileName: "deptImage/"+name+"logoMinPic"
                    }
                    this.disabledThree = false;
                    console.log(this.logoMinPicUrl);
                }
            },
            handleAdd,
            handleSubmit,
            onCancel
        }
    };
</script>


<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar-uploader-icon-oneImg {
        font-size: 28px;
        color: #8c939d;
        /*width: 178px;*/
        /*height: 178px;*/
        width: 250px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }

    .avatar-oneImg {
        width: 250px;
        height: 120px;
        display: block;
    }

    .avatar-uploader-icon-twoImg {
        font-size: 28px;
        color: #8c939d;
        width: 216px;
        height: 60px;
        line-height: 60px;
        text-align: center;
    }

    avatar-twoImg {
        width: 108px;
        height: 30px;
        display: block;
    }

    .avatar-uploader-icon-threeImg {
        font-size: 28px;
        color: #8c939d;
        width: 90px;
        height: 90px;
        line-height: 90px;
        text-align: center;
    }

    avatar-threeImg {
        width: 90px;
        height: 90px;
        display: block;
    }


</style>
